<template>
  <PageModal
    prevent-back
    show-back
    :show="show"
    :page-style="pageStyle"
    :footer-size="footerSize"
    :footer-style="footerStyle"
    :title="$t('selectFavorite.Title')"
    @back="closeModal"
    @close="closeModal"
  >
    <view class="favorite-box">
      <view class="programs-box">
        <view class="title-box">
          <view class="title">{{ $t('selectFavorite.SelectedProgram.Lable') }}</view>
          <view class="adjust" :class="{ disabled: adjustDisabled }" @click="adjustParameter">{{
            $t('selectFavorite.AdjustParams.Lable')
          }}</view>
        </view>
        <ProgramList
          :programs="programs"
          :active-key="activeProgramKey"
          :active-tips="activeProgramRemaining"
          @select="onProgramSelect"
        />
      </view>
    </view>

    <template #footer>
      <ActionButton :text="$t('selectFavorite.SelectedProgram.Save.Button')" :disabled="adjustDisabled" @click="save" />
    </template>

    <!-- 调节参数 -->
    <!-- <AdjustParameterModal
      v-model:show="adjustParameterVisible"
      custom-footer
      :control="control"
    >
      <template #footer>
        <view class="btn-box">
          <view class="btn cancel" @click="adjustParameter(false)">{{
            $t('selectFavorite.AdjustParams.Back.Button')
          }}</view>
          <view class="btn save" @click="save">{{ $t('selectFavorite.AdjustParams.Save.Button') }}</view>
        </view>
      </template>
    </AdjustParameterModal> -->
    <Modal
      :visible="favoriteFullVisible"
      :title="$t('selectFavorite.FavoriteFull.Dialog.Title')"
      :ok-text="$t('selectFavorite.FavoriteFull.Dialog.Ok.Button')"
      @ok="favoriteFullVisible = false"
    >
      <view class="notify-text">{{ $t('selectFavorite.FavoriteFull.Dialog.Content.Text') }}</view>
    </Modal>
  </PageModal>
</template>
<script setup lang="ts">
import ProgramList from '@/pages/appliance/components/programList.vue'
import AdjustParameterModal from '../view/adjustParameterModal.vue'
import Modal from '@/common/modal.vue'
import PageModal from '@/common/pageModal.vue'
import type { CSSProperties } from 'vue'
import { footerStyle, footerSize } from '@/layout/appliance/style'
import type { ApplianceProgram } from '@/types/appliance'
import { useI18n } from 'vue-i18n'
import {
  DISHWASHER_OPTION_FLEXSPRAY_BACKLEFT,
  DISHWASHER_OPTION_FLEXSPRAY_BACKRIGHT,
  DISHWASHER_OPTION_FLEXSPRAY_FRONTLEFT,
  DISHWASHER_OPTION_FLEXSPRAY_FRONTRIGHT,
  DISHWASHER_SILTENT_ON_DEMAND,
  START_IN_RELATIVE,
} from '@/constants/Command'
import type { FavoriteOptType } from '../Dishwasher/editFavoriteProgram/editFavoriteProgram.vue'
import { setSetting, type ApplianceDetailOption } from '@/api/appliance'
import {
  setFavorite,
  loadKeyIndex,
  getSettingsFavorite,
  filterFavoritePrograms,
} from '@/controller/common/Program/FavoriteHelper'
import type { CoffeeMakerController } from '@/controller/CoffeeMaker/definition'
import ActionButton from '@/common/actionButton/actionButton.vue'
import type { BaseController } from '@/controller/BaseAppliance/definition'
import { trackEvent, TrackType } from '@/dataReport/tracks'
import { safeTrack, applianceControlTrack } from '@/dataReport/dataReportUtil'

const pageStyle: CSSProperties = {
  backgroundColor: '#ffffff',
}
const i18n = useI18n()

const props = defineProps<{
  show: boolean
  control: BaseController.Control
}>()

const emit = defineEmits<{
  (e: 'update:show', show: boolean): void
  (e: 'close'): void
  (e: 'update-favorite'): void
}>()

function closeModal() {
  adjustParameterVisible.value = false
  emit('update:show', false)
  emit('close')
}

const favoriteFullVisible = ref(false)
const haId = computed(() => props.control.store._datasource.haId)
const programs = computed(() => filterFavoritePrograms(props.control.store.customizedAllPrograms || []))
const favoriteProgramsList = computed(() => props.control.store.favoriteProgramsList || [])
const activeProgramKey = computed(() => props.control.store.currentProgramKey)
const activeProgramName = computed(() => props.control.store.detail?.programName as string)
const settings = computed(() => props.control.store._datasource.settings)
const activeProgramRemaining = computed(() => props.control.store.programRemainingText)
const currentOptions = computed(() => props.control.store.detail?.option || [])
const adjustParameterVisible = ref(false)
const type = computed(() => props.control.store._datasource.type)
const allFavoriteLength = computed(() => {
  return getSettingsFavorite(settings.value).length
})
const adjustDisabled = computed(() => {
  if (activeProgramKey.value === '' || /^BSH\.Common\.Program\.Favorite\.(\d+)$/.test(activeProgramKey.value)) {
    return true
  } else {
    return false
  }
})

/**
 * slected program
 * @param program
 */
async function onProgramSelect(program: ApplianceProgram.Scope) {
  await props.control.store.setCurrentProgram(program)
}
/**
 * 保存
 */
function save() {
  // demo 模式不发数据 直接返回
  if (props.control.store.isVirtualAppliance) {
    closeModal()
    return
  }
  if (favoriteProgramsList.value?.length >= allFavoriteLength.value) {
    favoriteFullVisible.value = true
    return
  }
  try {
    uni.showLoading({
      title: i18n.t('APP.Common.Saving.Text'),
      mask: true,
    })
    if (type.value === 'Dishwasher') {
      setDishwasherFavorite()
    } else {
      setCoffeeMakerFavorite()
    }
    uni.hideLoading()
    uni.showToast({
      title: i18n.t('APP.Common.SaveSucess.Text'),
      icon: 'success',
    })
    closeModal()
  } catch (error) {
    uni.showToast({
      title: i18n.t('APP.Common.SaveFail.Text'),
      icon: 'error',
    })
  }
}
/**
 * 显示调节参数
 */
function adjustParameter() {
  emit('update-favorite')
}
/**
 * 保存洗碗机的收藏程序
 */
async function setDishwasherFavorite() {
  let submitParams: FavoriteOptType[] = [
    {
      key: activeProgramKey.value,
      name: programs.value.find((item) => item.key === activeProgramKey.value)?.name as string,
      value: [],
    },
  ]
  let newOptions = clearOptions(currentOptions.value) || []
  newOptions.forEach((item) => {
    submitParams[0].value.push({
      key: item.key as string,
      value: item.value as number,
      name: item.name as string,
    })
  })
  const keyIndex = loadKeyIndex('latest', activeProgramKey.value, settings.value)
  const key = `BSH.Common.Setting.Favorite.${keyIndex}.Program`
  await setSetting(haId.value, key, submitParams)
}
/**
 * 保存咖啡机的收藏程序
 */
async function setCoffeeMakerFavorite() {
  safeTrack(() => {
    trackEvent(
      'before_favorite_program',
      {
        program_key: activeProgramKey.value,
        program_name: activeProgramName.value,
      },
      TrackType.ApplianceDetail,
      'Appliance.CoffeeeMaker.AddFavorite.Favorite'
    )
  })
  const keyIndex = loadKeyIndex('latest', activeProgramKey.value, settings.value)
  let newOptions = [
    {
      key: activeProgramKey.value,
    },
  ]

  let res: any = null
  try {
    res = await setFavorite(haId.value, keyIndex, activeProgramName.value, newOptions)
  } catch (error) {
    res = error
  } finally {
    if (res === undefined) {
      res = {}
    }
    safeTrack(() => {
      trackEvent(
        'favorite_program',
        {
          program_key: activeProgramKey.value,
          program_name: activeProgramName.value,
          successOrNot: 'code' in res ? res.code == 0 : true,
          error_code: 'code' in res ? res.code : -1,
          response_msg: 'msg' in res ? res.msg : 'unknow',
        },
        TrackType.ApplianceDetail,
        'Appliance.CoffeeeMaker.AddFavorite.Favorite'
      )
    })
  }
}
/**
 * 清除options中多余数据
 * @param list
 */
function clearOptions(list: ApplianceDetailOption[]) {
  try {
    return list.filter(
      (item) =>
        ![
          START_IN_RELATIVE,
          DISHWASHER_SILTENT_ON_DEMAND,
          DISHWASHER_OPTION_FLEXSPRAY_FRONTLEFT,
          DISHWASHER_OPTION_FLEXSPRAY_BACKLEFT,
          DISHWASHER_OPTION_FLEXSPRAY_BACKRIGHT,
          DISHWASHER_OPTION_FLEXSPRAY_FRONTRIGHT,
        ].includes(item.key)
    )
  } catch (error) {}
}
</script>
<style scoped lang="less">
.disabled {
  opacity: 0.4;
  pointer-events: none;
}
.favorite-box {
  .programs-box {
    height: 100%;
    box-sizing: border-box;
    overflow: scroll;
    margin-top: 48rpx;

    .title-box {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 32rpx;
      .title {
        font-weight: 600;
        font-size: 48rpx;
        color: var(--dark-color);
      }
      .adjust {
        font-weight: 600;
        font-size: 28rpx;
        color: var(--primary-color);
      }
    }
  }
}
</style>
